package com.mke.config;

import com.mke.pojo.User;
import com.mke.service.IUserService;
import lombok.val;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>TODO</p>
 *
 * @author Oxygen
 * @version 1.0
 * @date 2022/4/26 16:48
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    IUserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 在数据库中创建相关的权限表格，在这里完成相关的编码执行授权操作
        // 拿到当前登录的对象：
        Subject subject = SecurityUtils.getSubject();
        // 在认证方法中 return new SimpleAuthenticationInfo("", user.getPassword(), "");的第一个参数传递user即可拿到User对象
        User currentUser = (User) subject.getPrincipal();

//        info.addStringPermission(currentUser.getPerms());
        info.addStringPermission("user:add");
        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=》认证doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        User user = userService.queryUserByAccount(userToken.getUsername());
        // 记得做返回数据验证
        if (user==null) {
            return null;
        }

        // 设置Session方便前端代码进行相关判断操作
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser", user);

//        if (!userToken.getUsername().equals(user.getAccount())) {
//            // return null 会自动抛出异常，账号错误
//            return null;
//        }
        // 密码认证,可以加密 MD5、MD5+SALT
        return new SimpleAuthenticationInfo("", user.getPassword(), "");
    }
}
